<?php
/**
 * 金币商城订单回调
 */
namespace app\common\model\order;

use app\common\model as M;
class GoldsGoods extends OrderAbtract
{
    /**
     * [paid_callback description]
     * @Author   FW
     * @DateTime 2021-09-18
     * 勿忘国耻，吾辈自强。
     * @Email    123763712@qq.com
     * @param    [type]           $order [description]
     * @return   [type]                  [description]
     */
    public function paid_callback( $order )
    {
        $outer = M\OrderOuterExchange::where('id',$order->order_outer_id)->find();
        if ( empty($outer) ) throw new \Exception('信息错误【0092】');

         ## 检查是否是代金券,
        $goods_type = M\GoldsGoods::where('id',$outer->goods_id)->value('goods_type');
        if ( $goods_type == M\GoldsGoods::GOOD_TYPE_COUPON ) {
            $outer->status = M\OrderOuterExchange::TYPE_RECIIVED;

            ## 发放代金券
            $coupon_id = M\GoodsRels::where('goods_id',$outer->goods_id)->where('rel_type',M\GoldsGoods::GOOD_TYPE_COUPON)->value('rel_id');
            $res = M\CouponRecords::addObtainRecord($uid = $order->uid , $coupon_id , $obtain_type = 4);
            if ( $res === false ) throw new \Exception('网络错误，请稍候再试【0093】');

        } else {
            $outer->status = M\OrderOuterExchange::TYPE_UNDELIVERY;
        }
        $res = $outer->save();
        if ( $res === false ) throw new \Exception('网络错误，请稍候再试【0092】');

        ## 有金币支付
        if ( $order->golds > 0 ) {
            $res = M\user\UserGoldsBill::add($amt = -$order->golds , $stype = M\user\UserGoldsBill::STYPE_EXCHANGE , $uid = $order->uid);
            if ( $res !== true ) throw new \Exception('扣减用户金币失败');
        }

        ## 减库存
        $res = M\GoldsGoods::where('id',$outer->goods_id)->setDec('goods_store',$outer->nums);
        if ( $res === false ) throw new \Exception('扣减库存失败');

        return true;
    }

    /** 获取订单编号前缀 */
    protected static function get_order_no_prefix()
    {
        return 'GO';
    }

    /** 获取订单类型 */
    protected static function get_order_type()
    {
        return \app\common\model\Order::ORDER_TYPE_GOLDS;
    }
} //Class End